package top.hzy520.common;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 15:37 2018/8/15
 */
@Aspect
@Component
public class DataSourceAspect {
    @Pointcut(value ="execution(* top.hzy520.*.service.*.*(..))" )
    public  void  pointCut(){}

    @Before(value = "pointCut()")
    public  void  doBefore(JoinPoint joinPoint) throws NoSuchMethodException {
        Object target=joinPoint.getTarget();
        String method=joinPoint.getSignature().getName();
        Class clazz=target.getClass();
        Class<?>[] parameterType=((MethodSignature)joinPoint.getSignature()).getMethod().getParameterTypes();
        Method method1=clazz.getMethod(method,parameterType);
        if (method1!=null&&method1.isAnnotationPresent(DataSource.class)){
            DataSource dataSource=method1.getAnnotation(DataSource.class);
            DynamicDataSourceHolder.setDataSource(dataSource.value());
        }
    }
}
